package com.example.transformer.controller;

import com.example.transformer.entity.ScanTask;
import com.example.transformer.entity.VulnerabilityResult;
import com.example.transformer.repository.ScanTaskRepository;
import com.example.transformer.repository.VulnerabilityResultRepository;
import com.example.transformer.service.AnalyzeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
public class UploadController {

    @Autowired
    private AnalyzeService analyzeService;

    @Autowired
    private ScanTaskRepository scanTaskRepository;

    @Autowired
    private VulnerabilityResultRepository vulnerabilityResultRepository;

    /**
     * 文件上传接口 - 接收Java文件并分析漏洞
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            System.out.println("📁 收到文件上传请求: " + file.getOriginalFilename());

            // 验证文件
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("文件不能为空"));
            }

            String filename = file.getOriginalFilename();
            if (filename == null || !filename.toLowerCase().endsWith(".java")) {
                return ResponseEntity.badRequest().body(createErrorResponse("只支持Java文件(.java)"));
            }

            // 读取文件内容
            String code = new String(file.getBytes(), StandardCharsets.UTF_8);
            if (code.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("文件内容为空"));
            }

            System.out.println("🔍 开始分析文件: " + filename + " (大小: " + code.length() + " 字符)");

            // 创建扫描任务记录
            ScanTask scanTask = new ScanTask(filename, code);
            scanTask.setStatus("PROCESSING");
            scanTask = scanTaskRepository.save(scanTask);

            // 调用分析服务
            Map<String, Object> result = analyzeService.analyzeCode(code);

            // 保存漏洞结果
            VulnerabilityResult vulnerabilityResult = new VulnerabilityResult(
                    scanTask,
                    (Boolean) result.get("has_vulnerability"),
                    (String) result.get("vulnerability_type"),
                    (Double) result.get("confidence"),
                    (String) result.get("location"),
                    extractCodeSnippet(code, (String) result.get("location"))
            );
            vulnerabilityResultRepository.save(vulnerabilityResult);

            // 更新扫描任务状态
            scanTask.setStatus("COMPLETED");
            scanTask.setCompletedAt(new Date());
            scanTaskRepository.save(scanTask);

            System.out.println("✅ 文件分析完成: " + filename);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            System.err.println("❌ 文件处理失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(
                    createErrorResponse("文件处理失败: " + e.getMessage())
            );
        }
    }

    /**
     * 获取扫描历史接口
     */
    @GetMapping("/scan-history")
    public ResponseEntity<List<ScanTask>> getScanHistory() {
        try {
            List<ScanTask> history = scanTaskRepository.findAll();
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(new ArrayList<>());
        }
    }

    /**
     * 获取特定扫描任务的漏洞结果
     */
    @GetMapping("/scan-results/{taskId}")
    public ResponseEntity<List<VulnerabilityResult>> getScanResults(@PathVariable Long taskId) {
        try {
            List<VulnerabilityResult> results = vulnerabilityResultRepository.findByScanTaskId(taskId);
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(new ArrayList<>());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("service", "Transformer Java代码审计系统");
        response.put("timestamp", System.currentTimeMillis());
        response.put("message", "服务运行正常");
        return ResponseEntity.ok(response);
    }

    /**
     * 直接分析代码接口
     */
    @PostMapping("/analyze/direct")
    public ResponseEntity<Map<String, Object>> analyzeDirect(@RequestBody Map<String, String> request) {
        try {
            String code = request.get("code");
            if (code == null || code.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("代码内容不能为空"));
            }

            System.out.println("🔍 收到直接代码分析请求，代码长度: " + code.length() + " 字符");
            Map<String, Object> result = analyzeService.analyzeCode(code);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            System.err.println("❌ 代码分析失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(
                    createErrorResponse("代码分析失败: " + e.getMessage())
            );
        }
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", true);
        error.put("message", message);
        error.put("has_vulnerability", false);
        return error;
    }

    /**
     * 从代码中提取片段
     */
    private String extractCodeSnippet(String code, String location) {
        if (location == null || !location.startsWith("Line ")) {
            return code.substring(0, Math.min(200, code.length()));
        }

        try {
            int lineNumber = Integer.parseInt(location.replace("Line ", ""));
            String[] lines = code.split("\n");
            if (lineNumber > 0 && lineNumber <= lines.length) {
                return lines[lineNumber - 1].trim();
            }
        } catch (NumberFormatException e) {
            // 忽略解析错误
        }

        return code.substring(0, Math.min(200, code.length()));
    }
}